//
//  CreateReceiverViewController.m
//  XDLookPic
//
//  Created by XD-XY on 5/26/14.
//  Copyright (c) 2014 XD-XY. All rights reserved.
//

#import "CreateReceiverViewController.h"
#import "AddressCell.h"

#define text_font   [UIFont boldSystemFontOfSize:15]
#define text_color  UIColorFromRGB(0x9d948a)
#define color2      UIColorFromRGB(0x999999)
@interface CreateReceiverViewController ()

@end

@implementation CreateReceiverViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
#pragma mark - 注册键盘通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleKeyboardDidShow:) name:UIKeyboardDidShowNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleKeyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    //反注册
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.titleLabel.text = @"编辑收件人";

    self.titleLabel.textColor = [UIColor whiteColor];
    dataArray = [[NSMutableArray alloc] init];
    dataArray2 = [[NSMutableArray alloc] init];
    dataArray3 = [[NSMutableArray alloc] init];
    
    provienceId = [[NSString alloc] init];
    cityId = [[NSString alloc] init];
    areaId = [[NSString alloc] init];
    lastProvienceId = [[NSString alloc] init];
    lastCityId = [[NSString alloc] init];
    lastAreaId = [[NSString alloc] init];
    
    addressLayer = @"provience";
    
    
    [self initViews];
    
    if ([_accessType isEqualToString:@"edit"]){
        [self getEditAddressData];
    }else if([_accessType isEqualToString:@"create"]){
        [self getAddressDatas:dataArray andTableName:@"provience" andProvience:@"1"];
    }
}

#pragma mark - Create UI
-(void)initViews
{
    CGFloat aheight = IOS7?20:0;
    
    UIButton * rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    rightBtn.frame = CGRectMake(320-117/2.0f, aheight, 117/2.0f, 44);
    [rightBtn setTitle:@"完成" forState:UIControlStateNormal];
    rightBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    rightBtn.backgroundColor = [UIColor clearColor];
    [rightBtn addTarget:self action:@selector(completeEdit) forControlEvents:UIControlEventTouchUpInside];
    [self.navigationBarView addSubview:rightBtn];
    
    
    scrollView = [[UIScrollView alloc] initWithFrame:self.contentView.bounds];
    scrollView.backgroundColor = [UIColor clearColor];
    scrollView.contentSize = CGSizeMake(UI_SCREEN_WIDTH, self.contentView.bounds.size.height);
    [self.contentView addSubview:scrollView];
    
    UILabel * receiverNameTag = [[UILabel alloc] initWithFrame:CGRectMake(0, 18, 90.5, 39.5)];
    receiverNameTag.backgroundColor = [UIColor clearColor];
    receiverNameTag.textAlignment = NSTextAlignmentRight;
    receiverNameTag.textColor = text_color;
    receiverNameTag.font = text_font;
    receiverNameTag.text = @"收货人姓名:";
    [scrollView addSubview:receiverNameTag];
    
    UIImageView * nameBgView = [[UIImageView alloc] initWithFrame:CGRectMake(width_x(receiverNameTag)+6, receiverNameTag.frame.origin.y, 397/2.0f, 79/2.0f)];
    nameBgView.image = [UIImage imageNamed:@"createborder"];
    nameBgView.userInteractionEnabled = YES;
    [scrollView addSubview:nameBgView];
    
    nameTF = [[UITextField alloc] initWithFrame:CGRectMake(5.5, 0, nameBgView.frame.size.width-5.5, nameBgView.frame.size.height)];
    nameTF.placeholder = @"输入收货人";
    nameTF.delegate = self;
    nameTF.textColor = color2;
    nameTF.font = [UIFont systemFontOfSize:14];
    nameTF.clearButtonMode = UITextFieldViewModeAlways;
    nameTF.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    [nameBgView addSubview:nameTF];
    
    
    UILabel * addressTag = [[UILabel alloc] initWithFrame:CGRectMake(0,height_y(receiverNameTag)+18.5, 90.5, 39.5)];
    addressTag.backgroundColor = [UIColor clearColor];
    addressTag.textAlignment = NSTextAlignmentRight;
    addressTag.textColor = text_color;
    addressTag.font = text_font;
    addressTag.text = @"所在地区:";
    [scrollView addSubview:addressTag];
    
    UIImageView * addressBgView = [[UIImageView alloc] initWithFrame:CGRectMake(width_x(addressTag)+6, addressTag.frame.origin.y, 397/2.0f, 79/2.0f)];
    addressBgView.image = [UIImage imageNamed:@"createborder"];
    addressBgView.userInteractionEnabled = YES;
    [scrollView addSubview:addressBgView];
    
    addressTF = [[UILabel alloc] initWithFrame:CGRectMake(5.5, 0, addressBgView.frame.size.width-5.5, addressBgView.frame.size.height)];
    addressTF.userInteractionEnabled = YES;
    addressTF.numberOfLines = 0;
    addressTF.backgroundColor = [UIColor clearColor];
    addressTF.text = @"选择所在地区";
    addressTF.textColor = color2;
    addressTF.font = [UIFont systemFontOfSize:14];
    [addressBgView addSubview:addressTF];
    
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(chooseProvienceidAndCityAndArea)];
    [addressTF addGestureRecognizer:tap];
    
    
    UILabel * detailAddressTag = [[UILabel alloc] initWithFrame:CGRectMake(0,height_y(addressTag)+17, 90.5, 39.5)];
    detailAddressTag.backgroundColor = [UIColor clearColor];
    detailAddressTag.textAlignment = NSTextAlignmentRight;
    detailAddressTag.textColor = text_color;
    detailAddressTag.font = text_font;
    detailAddressTag.text = @"详细地址:";
    [scrollView addSubview:detailAddressTag];
    
    UIImageView * detailAddressBgView = [[UIImageView alloc] initWithFrame:CGRectMake(width_x(detailAddressTag)+6, detailAddressTag.frame.origin.y, 397/2.0f, 199/2.0f)];
    detailAddressBgView.image = [UIImage imageNamed:@"createborder2"];
    detailAddressBgView.userInteractionEnabled = YES;
    [scrollView addSubview:detailAddressBgView];
    
    detailAddressTV = [[UITextView alloc] initWithFrame:CGRectMake(0, 0, detailAddressBgView.frame.size.width, detailAddressBgView.frame.size.height-15)];
    detailAddressTV.font = [UIFont systemFontOfSize:14];
    detailAddressTV.returnKeyType = UIReturnKeyDone;
    detailAddressTV.backgroundColor = [UIColor clearColor];
    detailAddressTV.delegate = self;
    detailAddressTV.textColor = color2;
    [detailAddressBgView addSubview:detailAddressTV];
    
    placeholderLB = [[UILabel alloc] initWithFrame:CGRectMake(5,9, 150, 14)];
    placeholderLB.backgroundColor = [UIColor clearColor];
    placeholderLB.text = @"长度在0-150字之间";
    placeholderLB.font = [UIFont systemFontOfSize:14];
    placeholderLB.textColor =color2;
    [detailAddressBgView addSubview:placeholderLB];
    

    UILabel * cLB = [[UILabel alloc] initWithFrame:CGRectMake(10,detailAddressBgView.frame.size.height-15,detailAddressBgView.frame.size.width-22, 15)];
    cLB.backgroundColor = [UIColor clearColor];
    cLB.textAlignment = NSTextAlignmentRight;
    cLB.text = @"/150";
    cLB.textColor = text_color;
    cLB.font = [UIFont systemFontOfSize:12];
    [detailAddressBgView addSubview:cLB];
    
    textNumberLB = [[UILabel alloc] initWithFrame:CGRectMake(10,detailAddressBgView.frame.size.height-15,detailAddressBgView.frame.size.width-22-25, 15)];
    textNumberLB.backgroundColor = [UIColor clearColor];
    textNumberLB.textColor = [UIColor redColor];
    textNumberLB.textAlignment = NSTextAlignmentRight;
    textNumberLB.text = [NSString stringWithFormat:@"%d",[detailAddressTV.text length]];
    textNumberLB.font = [UIFont systemFontOfSize:12];
    [detailAddressBgView addSubview:textNumberLB];
    
    UILabel * phoneTag = [[UILabel alloc] initWithFrame:CGRectMake(0,height_y(detailAddressBgView)+17.5, 90.5, 39.5)];
    phoneTag.backgroundColor = [UIColor clearColor];
    phoneTag.textAlignment = NSTextAlignmentRight;
    phoneTag.textColor = text_color;
    phoneTag.font = text_font;
    phoneTag.text = @"手机号码:";
    [scrollView addSubview:phoneTag];
    
    UIImageView * phoneBgView = [[UIImageView alloc] initWithFrame:CGRectMake(width_x(phoneTag)+6, phoneTag.frame.origin.y, 397/2.0f, 79/2.0f)];
    phoneBgView.image = [UIImage imageNamed:@"createborder"];
    phoneBgView.userInteractionEnabled = YES;
    [scrollView addSubview:phoneBgView];
    
    phoneTF = [[UITextField alloc] initWithFrame:CGRectMake(5.5, 0, phoneBgView.frame.size.width-5.5, phoneBgView.frame.size.height)];
    phoneTF.placeholder = @"输入手机号码";
    phoneTF.delegate = self;
    phoneTF.textColor = color2;
    phoneTF.font = [UIFont systemFontOfSize:14];
    phoneTF.clearButtonMode = UITextFieldViewModeAlways;
    phoneTF.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    phoneTF.keyboardType = UIKeyboardTypeNumberPad;
    [phoneBgView addSubview:phoneTF];
    
    
    UILabel * postcodeTag = [[UILabel alloc] initWithFrame:CGRectMake(0,height_y(phoneTag)+17.5, 90.5, 39.5)];
    postcodeTag.backgroundColor = [UIColor clearColor];
    postcodeTag.textAlignment = NSTextAlignmentRight;
    postcodeTag.textColor = text_color;
    postcodeTag.font = text_font;
    postcodeTag.text = @"邮政编码:";
    [scrollView addSubview:postcodeTag];
    
    UIImageView * postcodeBgView = [[UIImageView alloc] initWithFrame:CGRectMake(width_x(postcodeTag)+6, postcodeTag.frame.origin.y, 397/2.0f, 79/2.0f)];
    postcodeBgView.image = [UIImage imageNamed:@"createborder"];
    postcodeBgView.userInteractionEnabled = YES;
    [scrollView addSubview:postcodeBgView];
    
    postcodeTF = [[UITextField alloc] initWithFrame:CGRectMake(5.5, 0, postcodeBgView.frame.size.width-5.5, postcodeBgView.frame.size.height)];
    postcodeTF.placeholder = @"请输入邮政编码";
    postcodeTF.delegate = self;
    postcodeTF.textColor = color2;
    postcodeTF.font = [UIFont systemFontOfSize:14];
    postcodeTF.clearButtonMode = UITextFieldViewModeAlways;
    postcodeTF.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
    postcodeTF.keyboardType = UIKeyboardTypeNumberPad;
    [postcodeBgView addSubview:postcodeTF];
    
    [self createChooseCityViews];
    
}

#pragma mark - 创建城市选择View
-(void)createChooseCityViews
{
    chooseAd_BgView = [[UIView alloc] initWithFrame:self.view.bounds];
    chooseAd_BgView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:chooseAd_BgView];
    
    if (iPhone5){
        city_BgView = [[UIImageView alloc] initWithFrame:CGRectMake(23, height_y(self.navigationBarView)+26, 548/2.0f, 801/2.0f)];
    }else{
        city_BgView = [[UIImageView alloc] initWithFrame:CGRectMake(23, height_y(self.navigationBarView)+10, 548/2.0f, 801/2.0f)];
    }
    UILabel * label = [[UILabel alloc] initWithFrame:CGRectMake(0, 10, city_BgView.frame.size.width, 54)];
    label.text = @"请选择";
    label.textAlignment = NSTextAlignmentCenter;
    label.font = [UIFont systemFontOfSize:16.5];
    [city_BgView addSubview:label];
    label.backgroundColor = [UIColor clearColor];
    
    UIButton * closeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    closeBtn.frame = CGRectMake(225, 13.5, 34, 34);
    [closeBtn setBackgroundImage:[UIImage imageNamed:@"closeimg"] forState:UIControlStateNormal];
    [closeBtn addTarget:self action:@selector(closeChooseCity) forControlEvents:UIControlEventTouchDown];
    [city_BgView addSubview:closeBtn];
    
    city_BgView.image = [UIImage imageNamed:@"chooseaddressbgimg"];
    city_BgView.userInteractionEnabled = YES;
    [chooseAd_BgView addSubview:city_BgView];
    
    cityTableView = [[UITableView alloc] initWithFrame:CGRectMake(33-23,54+9, 254, 274) style:UITableViewStylePlain];
    cityTableView.backgroundColor = [UIColor clearColor];
    cityTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    cityTableView.delegate = self;
    cityTableView.dataSource = self;
    [city_BgView addSubview:cityTableView];
    
    lastBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    lastBtn.frame = CGRectMake(25,height_y(cityTableView)+15,66,26);
    [lastBtn setTitle:@"上一步" forState:UIControlStateNormal];
    lastBtn.titleLabel.font = [UIFont systemFontOfSize:13];
    [lastBtn setBackgroundImage:[UIImage imageNamed:@"next_nor_img"] forState:UIControlStateNormal];
    [lastBtn setBackgroundImage:[UIImage imageNamed:@"next_sel_img"] forState:UIControlStateHighlighted];
    [lastBtn addTarget:self action:@selector(lastBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [city_BgView addSubview:lastBtn];
    
    nextBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    nextBtn.frame = CGRectMake(183,height_y(cityTableView)+15,66,26);
    [nextBtn setTitle:@"下一步" forState:UIControlStateNormal];
    nextBtn.titleLabel.font = [UIFont systemFontOfSize:13];
    [nextBtn setBackgroundImage:[UIImage imageNamed:@"next_nor_img"] forState:UIControlStateNormal];
    [nextBtn setBackgroundImage:[UIImage imageNamed:@"next_sel_img"] forState:UIControlStateHighlighted];
    [nextBtn addTarget:self action:@selector(nextBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [city_BgView addSubview:nextBtn];
    
    [chooseAd_BgView setHidden:YES];
}

#pragma mark - UITextField Delegate
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if (textField == nameTF){
        [nameTF resignFirstResponder];
    }

    scrollView.contentSize = CGSizeMake(UI_SCREEN_WIDTH,self.contentView.bounds.size.height);
    [UIView animateWithDuration:0.5 animations:^{
        scrollView.contentOffset = CGPointMake(0, 0);
    } completion:^(BOOL finished) {
        
    }];
    
    return YES;
}

-(BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
//    textField.ke
    scrollView.contentSize = CGSizeMake(UI_SCREEN_WIDTH, self.contentView.bounds.size.height+100);
    if (textField == postcodeTF){
        scrollView.contentOffset = CGPointMake(0, 100);
    }
    if (textField == phoneTF||textField == postcodeTF){
        isNumberKeyBoard = YES;
        [self performSelector:@selector(handleKeyboardDidShow:) withObject:nil afterDelay:0.3];
    }else{
        isNumberKeyBoard = NO;
        if (doneInKeyboardButton.superview){
            [doneInKeyboardButton removeFromSuperview];
        }
    }
    
    return YES;
}

#pragma mark - UITextView Delegate
-(BOOL)textViewShouldBeginEditing:(UITextView *)textView
{
    scrollView.contentSize = CGSizeMake(UI_SCREEN_WIDTH, self.contentView.bounds.size.height+100);
    isNumberKeyBoard =NO;
    if (doneInKeyboardButton.superview){
        [doneInKeyboardButton removeFromSuperview];
    }
    return YES;
}

-(void)textViewDidChange:(UITextView *)textView
{
    if (IS_NOT_EMPTY(textView.text)){
        placeholderLB.hidden = YES;
    }else{
        placeholderLB.hidden = NO;
    }
    
    textNumberLB.text = [NSString stringWithFormat:@"%d",[textView.text length]];
}

-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if (range.length == 1){
        return YES;
    }
    
    if ([text isEqualToString:@"\n"]){
        [textView resignFirstResponder];
        scrollView.contentSize = CGSizeMake(UI_SCREEN_WIDTH, self.contentView.bounds.size.height);
        return NO;
    }
    
    if ([textView.text length]<150){
        return YES;
    }
    return NO;
}

#pragma mark - 实现键盘通知处理
- (void)handleKeyboardWillHide:(NSNotification *)notification
{
    if (!isNumberKeyBoard){
        return;
    }
    if (doneInKeyboardButton.superview)
    {
        [doneInKeyboardButton removeFromSuperview];
    }
    scrollView.contentSize = CGSizeMake(UI_SCREEN_WIDTH, self.contentView.bounds.size.height);
}

- (void)handleKeyboardDidShow:(NSNotification *)notification
{
    if (!isNumberKeyBoard){
        return;
    }
    // create custom button
    if (doneInKeyboardButton == nil)
    {
        doneInKeyboardButton = [UIButton buttonWithType:UIButtonTypeCustom];
        
        CGFloat screenHeight = [[UIScreen mainScreen] bounds].size.height;
        if(screenHeight==568.0f){//爱疯5
            doneInKeyboardButton.frame = CGRectMake(0, 568 - 53, 106, 53);
        }else{//3.5寸
            doneInKeyboardButton.frame = CGRectMake(0, 480 - 53, 106, 53);
        }
        
        doneInKeyboardButton.adjustsImageWhenHighlighted = NO;
        [doneInKeyboardButton setImage:[UIImage imageNamed:@"btn_done_up"] forState:UIControlStateNormal];
        [doneInKeyboardButton setImage:[UIImage imageNamed:@"btn_done_down"] forState:UIControlStateHighlighted];
        [doneInKeyboardButton addTarget:self action:@selector(finishAction) forControlEvents:UIControlEventTouchUpInside];
    }
    
    // locate keyboard view
    if ([[[UIApplication sharedApplication] windows] count]>1){
        UIWindow* tempWindow = [[[UIApplication sharedApplication] windows] objectAtIndex:1];
        if (doneInKeyboardButton.superview == nil)
        {
            [tempWindow addSubview:doneInKeyboardButton];    // 注意这里直接加到window上
            DDLOG(@"asdfdsfdsfdsfds");
        }
    }
}


-(void)finishAction{
    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];//关闭键盘
}


#pragma mark - UITableView Delegate
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 54;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if ([addressLayer isEqualToString:@"provience"]){
        return [dataArray count];
    }else if ([addressLayer isEqualToString:@"city"]){
        return [dataArray2 count];
    }
    return [dataArray3 count];
}

-(UITableViewCell * )tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * cellName = @"cell";
    AddressCell * cell = [tableView dequeueReusableCellWithIdentifier:cellName];
    if (cell == nil){
        cell = [[AddressCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellName];
        cell.backgroundColor = [UIColor whiteColor];
    }
    
    NSMutableArray * array;
    if ([addressLayer isEqualToString:@"provience"]){
        if ([dataArray count]==0){
            return nil;
        }
        array = dataArray;
    }else if ([addressLayer isEqualToString:@"city"]){
        if ([dataArray2 count]==0){
            return nil;
        }
        array = dataArray2;
    }else{
        if ([dataArray3 count]==0){
            return nil;
        }
        array = dataArray3;
    }
    
    NSDictionary * dict = [array objectAtIndex:indexPath.row];
    
    if([dict[@"status"] isEqualToString:@"0"]){
        [cell.selectBtn setBackgroundImage:[UIImage imageNamed:@"choose_no_img"] forState:UIControlStateDisabled];
    }else{
        [cell.selectBtn setBackgroundImage:[UIImage imageNamed:@"choose_yes_img"] forState:UIControlStateDisabled];
    }
    cell.titleLB.text = dict[@"name"];

    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString * parentid;
    if ([addressLayer isEqualToString:@"provience"]){
        parentid = [dataArray objectAtIndex:indexPath.row][@"id"];
        provienceId = parentid;
        for (int i = 0 ; i <[dataArray count];i++){
            NSMutableDictionary * dict = [dataArray objectAtIndex:i];
            if (i == indexPath.row){
                [dict setValue:@"1" forKey:@"status"];
            }else{
                [dict setValue:@"0" forKey:@"status"];
            }
        }
    }else if ([addressLayer isEqualToString:@"city"]){
        parentid = [dataArray2 objectAtIndex:indexPath.row][@"id"];
        cityId = parentid;
        for (int i = 0 ; i <[dataArray2 count];i++){
            NSMutableDictionary * dict = [dataArray2 objectAtIndex:i];
            if (i == indexPath.row){
                [dict setValue:@"1" forKey:@"status"];
            }else{
                [dict setValue:@"0" forKey:@"status"];
            }
        }
    }else if ([addressLayer isEqualToString:@"area"]){
        parentid = [dataArray3 objectAtIndex:indexPath.row][@"id"];
        areaId = parentid;
        for (int i = 0 ; i <[dataArray3 count];i++){
            NSMutableDictionary * dict = [dataArray3 objectAtIndex:i];
            if (i == indexPath.row){
                [dict setValue:@"1" forKey:@"status"];
            }else{
                [dict setValue:@"0" forKey:@"status"];
            }
        }
    }
    [cityTableView reloadData];
    
    [self performSelector:@selector(delayPerformSegue:) withObject:parentid afterDelay:0.3];
    
}

-(void)delayPerformSegue:(NSString *)parentid
{
    lastBtn.hidden = NO;
    if ([addressLayer isEqualToString:@"provience"]){
        cityId = nil;
        areaId =nil;
        [self getAddressDatas:dataArray2 andTableName:@"city" andProvience:parentid];
    }else if ([addressLayer isEqualToString:@"city"]){
        areaId = nil;
        [self getAddressDatas:dataArray3 andTableName:@"area" andProvience:parentid];
    }else{
        chooseAd_BgView.hidden =YES;
        NSString * str1 = [self getNameWithTable:@"provience" andId:provienceId];
        NSString * str2 = [self getNameWithTable:@"city" andId:cityId];
        NSString * str3 = [self getNameWithTable:@"area" andId:areaId];
        addressTF.text = [NSString stringWithFormat:@"%@%@%@",str1,str2,str3];
        
        lastProvienceId = [NSString stringWithFormat:@"%@",provienceId];
        lastCityId = [NSString stringWithFormat:@"%@",cityId];
        lastAreaId = [NSString stringWithFormat:@"%@",areaId];
    }
}

#pragma mark - 从数据库中取地理位置
-(void)getAddressDatas:(NSMutableArray *)array andTableName:(NSString *)name andProvience:(NSString *)parentid
{
    addressLayer = name;
    FMDatabase * db = [XDTools getDb];
    if (![db open]){
        DDLOG(@"open fail!");
        return;
    }
    
    [array removeAllObjects];
    NSString *queryString=[NSString stringWithFormat:@"SELECT * FROM %@ where parentid = ?",name];
    FMResultSet * rs = [db executeQuery:queryString,parentid];
    int i = 0;
    while ([rs next]) {
        i++;
        NSMutableDictionary * dict;
        if(i==1){
            dict = [[NSMutableDictionary alloc] initWithObjects:@[[rs objectForColumnName:@"id"],[rs objectForColumnName:@"name"],[rs objectForColumnName:@"parentid"],@"1"] forKeys:@[@"id",@"name",@"parentid",@"status"]];
            if([name isEqualToString:@"provience"]){
                provienceId = [[rs objectForColumnName:@"id"] stringValue];
            }else if ([name isEqualToString:@"city"]){
                cityId = [[rs objectForColumnName:@"id"] stringValue];
            }else{
                areaId = [[rs objectForColumnName:@"id"] stringValue];
            }
        }else{
            dict = [[NSMutableDictionary alloc] initWithObjects:@[[rs objectForColumnName:@"id"],[rs objectForColumnName:@"name"],@"0"] forKeys:@[@"id",@"name",@"status"]];
        }
        
        [array addObject:dict];
    }
    [db close];
    
    
    [cityTableView reloadData];
}

#pragma mark - 遍历数据库,通过id取name
-(NSString *)getNameWithTable:(NSString *)table andId:(NSString *)cid
{
    FMDatabase * db = [XDTools getDb];
    if (![db open]){
        DDLOG(@"open fail!");
        return nil;
    }

    NSString *queryString=[NSString stringWithFormat:@"SELECT * FROM %@ where id = ?",table];
    FMResultSet * rs = [db executeQuery:queryString,cid];
    while ([rs next]) {
        return [rs objectForColumnName:@"name"];
    }
    return nil;
}

#pragma mark - 选择所在地区
-(void)chooseProvienceidAndCityAndArea
{
    [nameTF resignFirstResponder];
    [detailAddressTV resignFirstResponder];
    [phoneTF resignFirstResponder];
    [postcodeTF resignFirstResponder];
    
    chooseAd_BgView.transform = CGAffineTransformMakeScale(0, 0);
    [UIView animateWithDuration:0.2 animations:^{
        chooseAd_BgView.transform = CGAffineTransformIdentity;
    } completion:^(BOOL finished) {
        [UIView animateWithDuration:0.1 animations:^{
            chooseAd_BgView.transform=CGAffineTransformScale(chooseAd_BgView.transform, 1.1, 1.1);
        } completion:^(BOOL finished) {
            [UIView animateWithDuration:0.1 animations:^{
                chooseAd_BgView.transform = CGAffineTransformIdentity;
            } completion:^(BOOL finished) {
                
            }];
        }];
    }];
    [lastBtn setHidden:YES];
    [chooseAd_BgView setHidden:NO];
    
    addressLayer = @"provience";
    [cityTableView reloadData];
}

#pragma mark - 取消地区选择
-(void)closeChooseCity
{
    [chooseAd_BgView setHidden:YES];
}

#pragma mark - 选择地区“上一步”
-(void)lastBtnClick
{
    DDLOG_CURRENT_METHOD;
    if([addressLayer isEqualToString:@"provience"]){
        return;
    }else if([addressLayer isEqualToString:@"city"]){
        addressLayer = @"provience";
        cityId = nil;
        lastBtn.hidden =YES;
        
    }else if ([addressLayer isEqualToString:@"area"]){
        addressLayer = @"city";
        areaId = nil;
    }
    [cityTableView reloadData];
}

#pragma mark - 选择地区"下一步"
-(void)nextBtnClick
{
    if([addressLayer isEqualToString:@"provience"]){
        int a = 0;
        for (int i =0;i<[dataArray count];i++){
            NSDictionary * dict  = [dataArray objectAtIndex:i];
            if ([[dict valueForKey:@"status"] isEqualToString:@"1"]){
                a= i;
                break;
            }
        }
        NSIndexPath * index = [NSIndexPath indexPathForRow:a inSection:0];
        [self tableView:cityTableView didSelectRowAtIndexPath:index];
    }else if ([addressLayer isEqualToString:@"city"]){
        int a = 0;
        for (int i =0;i<[dataArray2 count];i++){
            NSDictionary * dict  = [dataArray2 objectAtIndex:i];
            if ([[dict valueForKey:@"status"] isEqualToString:@"1"]){
                a= i;
                break;
            }
        }
        NSIndexPath * index = [NSIndexPath indexPathForRow:a inSection:0];
        [self tableView:cityTableView didSelectRowAtIndexPath:index];
    }else{
        int a = 0;
        for (int i =0;i<[dataArray3 count];i++){
            NSDictionary * dict  = [dataArray3 objectAtIndex:i];
            if ([[dict valueForKey:@"status"] isEqualToString:@"1"]){
                a= i;
                break;
            }
        }
        NSIndexPath * index = [NSIndexPath indexPathForRow:a inSection:0];
        [self tableView:cityTableView didSelectRowAtIndexPath:index];
    }
}

#pragma mark - 完成编辑
-(void)completeEdit
{
    DDLOG_CURRENT_METHOD;
    [nameTF resignFirstResponder];
    [addressTF resignFirstResponder];
    [detailAddressTV resignFirstResponder];
    [phoneTF resignFirstResponder];
    [postcodeTF resignFirstResponder];
    
    if (!IS_NOT_EMPTY(nameTF.text)){
        [XDTools showTips:@"请填写收货人姓名" toView:mWindow];
        return;
    }
    if (!IS_NOT_EMPTY(lastAreaId)){
        [XDTools showTips:@"请填写所在地区" toView:mWindow];
        return;
    }
    if (!IS_NOT_EMPTY(detailAddressTV.text)){
        [XDTools showTips:@"请填写详细地址" toView:mWindow];
        return;
    }
    if (!IS_NOT_EMPTY(phoneTF.text)){
        [XDTools showTips:@"请填写手机号码" toView:mWindow];
        return;
    }
    if(!IS_NOT_EMPTY(postcodeTF.text)){
        [XDTools showTips:@"请填写邮政编码" toView:mWindow];
        return;
    }
    NSString * uid = [[[NSUserDefaults standardUserDefaults] objectForKey:@"MYSELF_INFO"] objectForKey:@"uid"];
    uid = @"1290680";
    NSDictionary * params;
    NSString * api;
    if ([_accessType isEqualToString:@"create"]){
        params= @{@"userID":uid,
                  @"provincesID":lastProvienceId,
                  @"cityID":lastCityId,
                  @"areaID":lastAreaId,
                  @"address":detailAddressTV.text,
                  @"userName":nameTF.text,
                  @"code":postcodeTF.text,
                  @"phone":phoneTF.text
                  };
        api = API_ADDADDRESS;
    }else {
        params= @{@"userID":uid,
                  @"provincesID":lastProvienceId,
                  @"cityID":lastCityId,
                  @"areaID":lastAreaId,
                  @"address":detailAddressTV.text,
                  @"userName":nameTF.text,
                  @"code":postcodeTF.text,
                  @"phone":phoneTF.text,
                  @"addressID":_addressid
                  };
        api = API_EDITADDRESS;
    }
    
    
    ASIHTTPRequest *request = [XDTools getShopRequestWithDict:params API:api];
    __weak ASIHTTPRequest * mrequest = request;

    [request setCompletionBlock:^{
        [XDTools hideProgress:mWindow];
        NSDictionary *tempDict = [XDTools  JSonFromString:[mrequest responseString]];
        if([tempDict[@"status"] intValue]==1){
            [_delegate theRecerverHadEditSucess];
            [self performSelector:@selector(gotoBack) withObject:nil afterDelay:1.0f];
        }else{
            [XDTools showTips:tempDict[@"msg"] toView:mWindow];
        }
    }];
    
    [request setFailedBlock:^{
        [XDTools hideProgress:mWindow];
        if (mrequest.error.code == 2) {
            [XDTools showTips:@"网络请求超时" toView:self.view];
        }
    }];
    
    [request startAsynchronous];
    [XDTools showProgress:mWindow];
}

-(void)gotoBack
{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - 获取编辑收货人信息
-(void)getEditAddressData
{
    NSString * uid = [[[NSUserDefaults standardUserDefaults] objectForKey:@"MYSELF_INFO"] objectForKey:@"uid"];
    NSDictionary * params = @{@"userID":uid,
                              @"addressID":_addressid
                              };
    
    ASIHTTPRequest *request = [XDTools getShopRequestWithDict:params API:API_ADDRESSDETAIL];
    __weak ASIHTTPRequest * mrequest = request;

    [request setCompletionBlock:^{
        [XDTools hideProgress:mWindow];
        NSDictionary *tempDict = [XDTools  JSonFromString:[mrequest responseString]];
        DDLOG(@"tempDict = %@",tempDict);
        if([tempDict[@"status"] intValue]==1){
            if (tempDict[@"data"]){
                nameTF.text = tempDict[@"data"][@"username"];
                detailAddressTV.text = tempDict[@"data"][@"address"];
                phoneTF.text = tempDict[@"data"][@"mobile"];
                postcodeTF.text =tempDict[@"data"][@"zipcode"];
                
                if(IS_NOT_EMPTY(detailAddressTV.text)){
                    placeholderLB.hidden = YES;
                    textNumberLB.text = [NSString stringWithFormat:@"%d",[detailAddressTV.text length]];
                }
                
                lastProvienceId = provienceId = [NSString stringWithFormat:@"%@",tempDict[@"data"][@"province"]];
                lastCityId = cityId = [NSString stringWithFormat:@"%@",tempDict[@"data"][@"city"]];
                lastAreaId = areaId = [NSString stringWithFormat:@"%@",tempDict[@"data"][@"district"]];
                
                NSString * str1 = [self getNameWithTable:@"provience" andId:lastProvienceId];
                NSString * str2 = [self getNameWithTable:@"city" andId:lastCityId];
                NSString * str3 = [self getNameWithTable:@"area" andId:lastAreaId];
        
                addressTF.text = [NSString stringWithFormat:@"%@%@%@",str1,str2,str3];
                
                [self getAddressDatas:dataArray andTableName:@"provience" andProvience:@"1"];
            }
            
        }else{
            [XDTools showTips:tempDict[@"msg"] toView:mWindow];
        }
    }];
    
    [request setFailedBlock:^{
        [XDTools hideProgress:mWindow];
        if (mrequest.error.code == 2) {
            [XDTools showTips:@"网络请求超时" toView:self.view];
        }
    }];
    
    [request startAsynchronous];
    [XDTools showProgress:mWindow];

}

#pragma mark - 重写父类返回方法
- (void)backPrePage
{
    UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"" message:@"是否放弃编辑" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [alert show];
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1){
        [nameTF resignFirstResponder];
        [addressTF resignFirstResponder];
        [detailAddressTV resignFirstResponder];
        [phoneTF resignFirstResponder];
        [postcodeTF resignFirstResponder];
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
